package oyl.selenium.config.translate.baidu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.util.StringUtils;
import oyl.selenium.config.translate.DouyinTranslateDemo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class BaiduTranslateDemo {
    public static final String translateUrl = "http://api.fanyi.baidu.com/api/trans/vip/translate?q=apple&from=en&to=zh&appid=20220923001352273&salt=1435660288&sign=KQ9Iyw4FUCXteBJPBDJb";

    // 在平台申请的APP_ID 详见 http://api.fanyi.baidu.com/api/trans/product/desktop?req=developer
    private static final String APP_ID = "20220923001352273";
    private static final String SECURITY_KEY = "KQ9Iyw4FUCXteBJPBDJb";
    private static final TransApi api = new TransApi(APP_ID, SECURITY_KEY);

    public static final Map<String, String> cache = new HashMap<>();

    public static void main(String[] args) {

        //String query = "高度600米";
        //System.out.println(api.getTransResult(query, "auto", "en"));
        String sourceLang = "en", targetLang = "ara";
        String article = "Product Brand: SINOVINYL<sup>®</sup>\n\n" +
                "Item color: super gloss crystal sapphire blue\n\n" +
                "Item code: CL-SV-24\n\n" +
                "Install type: full car body wrap\n\n" +
                "<b><strong>Product technology</strong></b>\n" +
                "1. High polymeric double casting\n\n" +
                "2. Air free TECH+\n\n" +
                "3. Micro air channel\n\n" +
                "4. Low initial tack\n\n" +
                "5. Super stretch\n\n" +
                "6. Long time durability\n\n" +
                "Browse Super Gloss Crystal Sapphire Blue more informations: <a href=\"https://www.sinovinyl.com/product/gloss-crystal-vinyl-car-wrap/\"> https://www.sinovinyl.com/product/gloss-crystal-vinyl-car-wrap/</a>\n\n" +
                "<img src=\"https://www.sinovinyl.com/wp-content/uploads/2022/09/CL-SV-24-1.jpg\" alt=\"CL-SV-24 Super Gloss Crystal Sapphire Blue Vinyl Vehicle Wrap Supplier For INFINITI\" width=\"800\" />\n" +
                "<img src=\"https://www.sinovinyl.com/wp-content/uploads/2022/09/CL-SV-24-2.jpg\" alt=\"CL-SV-24 Super Gloss Crystal Sapphire Blue Vinyl Vehicle Wrap Supplier For INFINITI\" width=\"800\" />\n" +
                "<img src=\"https://www.sinovinyl.com/wp-content/uploads/2022/09/CL-SV-24-3.jpg\" alt=\"CL-SV-24 Super Gloss Crystal Sapphire Blue Vinyl Vehicle Wrap Supplier For INFINITI\" width=\"800\" />\n" +
                "<img src=\"https://www.sinovinyl.com/wp-content/uploads/2022/09/CL-SV-24-4.jpg\" alt=\"CL-SV-24 Super Gloss Crystal Sapphire Blue Vinyl Vehicle Wrap Supplier For INFINITI\" width=\"800\" />\n" +
                "<img src=\"https://www.sinovinyl.com/wp-content/uploads/2022/09/CL-SV-24-5.jpg\" alt=\"CL-SV-24 Super Gloss Crystal Sapphire Blue Vinyl Vehicle Wrap Supplier For INFINITI\" width=\"800\" />\n" +
                "<img src=\"https://www.sinovinyl.com/wp-content/uploads/2022/09/CL-SV-24-6.jpg\" alt=\"CL-SV-24 Super Gloss Crystal Sapphire Blue Vinyl Vehicle Wrap Supplier For INFINITI\" width=\"800\" />";

        String res = translateArtice(sourceLang, targetLang, article);
        System.out.println(res);
//        System.out.println(translateText("en", "zh", article));
    }

    public static String translateArtice(String sourceLang, String targetLang, String article) {
        String[] items = article.replaceAll("\n\n", "\n").split("\n");
        StringBuffer res = new StringBuffer();
        for (int i = 0; i < items.length; i++) {
            String item = items[i];
            switch (i) {
                case 0:// Product Brand: SINOVINYL<sup>®</sup>
                    res.append(BaiduTranslateDemo.patternTranslate(sourceLang, targetLang, item, "(.*)(?=SINOVINYL<sup>)")).append("<br>").append("<br>");
                    break;
                case 1:
                case 3:
                    res.append(BaiduTranslateDemo.translateText(sourceLang, targetLang, item)).append("<br>").append("<br>");
                    break;
                case 2:
                    res.append(BaiduTranslateDemo.patternTranslate(sourceLang, targetLang, item, "(.*)(?=:)")).append("<br>").append("<br>");
                    break;
                case 4://<b><strong>Product technology</strong></b>
                    res.append(BaiduTranslateDemo.patternTranslate(sourceLang, targetLang, item, "(?<=<b><strong>)(.*?)(?=</strong></b>)")).append("<br>");
                    break;
                case 5:
                case 6:
                case 7:
                case 8:
                case 9:
                case 10:
                    res.append(BaiduTranslateDemo.patternTranslate(sourceLang, targetLang, item, "(?<=[0-9]\\.)(.*)")).append("<br>").append("<br>");
                    break;
                case 11://Browse Super Gloss Crystal Sapphire Blue more informations: <a href="https://www.sinovinyl.com/product/gloss-crystal-vinyl-car-wrap/"> https://www.sinovinyl.com/product/gloss-crystal-vinyl-car-wrap/</a>
                    res.append(BaiduTranslateDemo.patternTranslate(sourceLang, targetLang, item, "(.*)(?=<a href.*>)")).append("<br>").append("<br>");
                    break;
                case 12://<img src="https://www.sinovinyl.com/wp-content/uploads/2022/09/CL-SV-24-1.jpg" alt="CL-SV-24 Super Gloss Crystal Sapphire Blue Vinyl Vehicle Wrap Supplier For INFINITI" width="800" />
                case 13:
                case 14:
                case 15:
                case 16:
                case 17:
                    res.append(BaiduTranslateDemo.patternTranslate(sourceLang, targetLang, item, "(?<= alt=\")(.*?)(?=\")")).append("<br>");
                    break;
            }
        }
        return res.toString();
    }

    private static String patternTranslate(String sourceLang, String targetLang, String article, String pattern) {
        Pattern r = Pattern.compile(pattern);
        Matcher m = r.matcher(article);
        List<String> urls = new ArrayList<>();
        while (m.find()) {
            for (int i = 0; i < m.groupCount(); i++) {
                //System.out.println(i+"Found value: " + m.group(i));
                urls.add(BaiduTranslateDemo.translateText(sourceLang, targetLang, m.group(i)));
            }
        }
        article = String.format(article.replaceAll(pattern, "%s"), urls.toArray());
        return article;
    }

    public static String translateText(String sourceLang, String targetLang, String text) {
        if (StringUtils.isEmpty(text)) {
            return "";
        }
        String cacheKey = String.format("%s_%s_%s", sourceLang, targetLang, text);
        if (cache.containsKey(cacheKey)) {
            return cache.get(cacheKey);
        }
        String res = "";
        try {
            Thread.currentThread().sleep(300);
            if (targetLang.equals("tr")) {
                // 土耳其百度没有，改用抖音
                res = DouyinTranslateDemo.translateText(text, sourceLang, targetLang);
            } else {
                res = api.getTransResult(text, sourceLang, targetLang);
                //System.out.println(JSONObject.toJSONString(JSONObject.parseObject(res),true));
                res = ((JSONObject) ((JSONArray) JSONObject.parseObject(res).get("trans_result")).get(0)).get("dst").toString().replaceAll(" - ", "-").replaceAll("-sv-", "-SV-");
            }
            cache.put(cacheKey, res);
            return res;
        } catch (Exception ex) {
            System.out.println(String.format("翻译异常%s_%s_%s_%s", sourceLang, targetLang, text, res));
        }
        return "";
    }
}
